package com.brspace.qualitycontrol.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.brspace.qualitycontrol.entity.*;
import com.brspace.qualitycontrol.entity.Process;
import com.brspace.qualitycontrol.entity.vo.LetterListVo;
import com.brspace.qualitycontrol.entity.vo.LetterQueryVo;
import com.brspace.qualitycontrol.entity.vo.LetterStateVo;
import com.brspace.qualitycontrol.mapper.*;
import com.brspace.qualitycontrol.service.LetterService;
import com.brspace.qualitycontrol.utils.DateTimeUtil;
import com.brspace.qualitycontrol.utils.EmptyUtil;
import com.brspace.qualitycontrol.utils.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.*;

/**
 * <p>
 * 信访诉求 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2021-04-09
 */
@Service
public class LetterServiceImpl extends ServiceImpl<LetterMapper, Letter> implements LetterService {
    @Resource
    private ProcessMapper processMapper;
    @Resource
    private ProcessNodeMapper nodeMapper;
    @Resource
    private ProcessRouterMapper routerMapper;
    @Resource
    private HandleMapper handleMapper;
    @Resource
    private PeopleHotlineMapper peopleHotlineMapper;
    @Resource
    private IncomingCallMapper callMapper;
    @Resource
    private TownMatterMapper townMatterMapper;

    /**
     * 审核
     * @Author wangt
     * @Date 2021-04-30 15:36:17
     */
    @Override
    public R examine(Letter letter, String xiaUser, String dangUser) {
        System.err.println(letter);
        if (letter.getNodeId()==0) {
            throw new SecurityException("流程已结束！");
        }
        if ("退回".equals(letter.getProgress())){
            if ("undefined".equals(xiaUser) || xiaUser==null || "null".equals(xiaUser)){
                Handle handleList = handleMapper.selectOne(new QueryWrapper<Handle>().eq("middleman_id", dangUser).eq("document_id", letter.getId()).eq("n_id",letter.getNodeId()));
                xiaUser=handleList.getHandleId();
            }
        }
        // 根据当前节点获取当前流程下的PID以及节点NodeName
        ProcessNode processNode = nodeMapper.selectOne(new QueryWrapper<ProcessNode>().eq("id", letter.getNodeId()));
        // 获取初始节点的ID
        int findId = nodeMapper.selectOne(new QueryWrapper<ProcessNode>().eq("p_id", processNode.getPId()).eq("sort_num", 1)).getId();
        // 获取最后节点的ID
        int id = nodeMapper.selectOne(new QueryWrapper<ProcessNode>().eq("p_id", processNode.getPId()).orderByDesc("sort_num").last("limit 1")).getId();
        if (letter.getNodeId()==findId) {
            // 获取目标节点
            handleAdd(letter, letter.getDoUser(), null, processNode.getPId());
            int i = routerMapper.selectOne(new QueryWrapper<ProcessRouter>().eq("current_id", letter.getNodeId()).eq("requirement",letter.getProgress())).getTargetId();
            letter.setNodeId(i);
            letter.setState("0");
            handleAdd(letter, xiaUser, letter.getDoUser(), processNode.getPId());
            baseMapper.updateById(letter);
            return R.ok();
        }
        // 获取当前节点的信息
        List<ProcessRouter> processRouters = routerMapper.selectList(new QueryWrapper<ProcessRouter>().eq("current_id", letter.getNodeId()).eq("requirement", letter.getProgress()));
        if ("同意".equals(letter.getProgress())){
            examineIf(letter,processRouters,id,dangUser,xiaUser,processNode.getPId());
            return R.ok();
        }
        if ("转接收".equals(letter.getProgress())){
            xiaUser=letter.getDoUser();
            examineIf(letter,processRouters,id,dangUser,xiaUser,processNode.getPId());
            return R.ok();
        }
        if ("退回".equals(letter.getProgress())){
            for (ProcessRouter router : processRouters) {
                System.err.println("驳回");
                letter.setState("0");
                letter.setNodeId(router.getTargetId());
                Handle handle = new Handle();
                handle.setDocumentId(letter.getId())
                        .setHandleId(xiaUser)
                        .setMiddlemanId(dangUser)
                        .setPId(processNode.getPId());
                handleMapper.insert(handle);
                baseMapper.updateById(letter);
                return R.ok();
            }
        }

        return R.error().data("message","问就是出现异常！");
    }

    private void examineIf(Letter letter, List<ProcessRouter> processRouters, int id, String dangUser, String xiaUser, int pId) {
        for (ProcessRouter router : processRouters) {
            if (router.getTargetId()==id){
                System.err.println("目标节点等于最后节点");
                letter.setState("1");
                letter.setNodeId(0);
                Handle handle = new Handle();
                handle.setDocumentId(letter.getId())
                        .setHandleId(dangUser)
                        .setNId(router.getTargetId())
                        .setPId(router.getPId());
                handleMapper.insert(handle);
                baseMapper.updateById(letter);
            }else {
                if ("undefined".equals(xiaUser) || xiaUser==null || "null".equals(xiaUser)){
                    throw new SecurityException("请选择下阶段办理人！");
                }
                System.err.println("进入下一个节点");
                letter.setState("0");
                letter.setNodeId(router.getTargetId());
                handleAdd(letter,xiaUser,dangUser, pId);
                baseMapper.updateById(letter);
            }
        }
    }

    private void handleAdd(Letter letter, String daiId, String xianId, int id) {
//        handleMapper.delete(new QueryWrapper<Handle>().eq("document_id", letter.getId()).eq("middleman_id", daiId));
//        handleMapper.delete(new QueryWrapper<Handle>().eq("document_id", letter.getId()).eq("handle_id", daiId));
        Handle handle = new Handle();
        if (daiId==null){
            handle.setMiddlemanId(letter.getDoRen());
        }else {
            handle.setMiddlemanId(daiId);
        }
        handle.setDocumentId(letter.getId())
                .setHandleId(xianId)
                .setPId(id).setNId(letter.getNodeId());
        handleMapper.insert(handle);
    }

    @Override
    public R add(Letter letter) {
        this.check(letter);
        letter.setState("1");
        try {
            int i = DateTimeUtil.getDayDiffer(letter.getLetterTime(), letter.getTermReply());
            if (i>=letter.getDateNumber()){
                letter.setStateType("1");
            }
            if (i<= letter.getDateNumber()){
                letter.setStateType("0");
            }
        } catch (ParseException e) {
            e.printStackTrace();
            throw  new SecurityException("日期格式错误！");
        }
        try {
            // 获取节点
            int id = processMapper.selectOne(new QueryWrapper<Process>().eq("flow_name", "信访诉求")).getId();
            letter.setNodeId(nodeMapper.selectOne(new QueryWrapper<ProcessNode>().eq("p_id", id).eq("sort_num", "1")).getId());
        } catch (Exception e) {
            e.printStackTrace();
            throw new SecurityException("路由或节点存在异常，请联系管理员！");
        }
        int i = baseMapper.insert(letter);
        if (i>0) {
            letter.setProgress("同意");
            this.examine(letter,letter.getFenId(),letter.getDoUser());
            return R.ok().message("录入成功！");
        }
        return R.error().message("录入失败！");
    }

    @Override
    public R selectPage1(int page, int limit, Object o, String id) {
        // 代办
        List<Letter> list1 = new ArrayList<>();
        // 获取当前登录用户所对应要进行审批处理的数据
        List<Letter> list = baseMapper.selectList(new QueryWrapper<Letter>()
                .eq("do_user", id).or().eq("fen_id", id)
                .or().eq("ke_id", id).or().eq("cheng_user", id));
        if (list == null) {
            return R.ok().data("rows", null).data("total", 0);
        }
        for (Letter letter : list) {
            // 代办数量
            Integer integer1 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", letter.getId()).eq("middleman_id", id));
            // 已办数量
            Integer integer2 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", letter.getId()).eq("handle_id", id));
            // 代办
            if (integer1 > integer2) {
                list1.add(letter);
            }
        }
        return R.ok().data("rows", page(list1, limit, page)).data("total", list1.size());
    }

    @Override
    public R stateList1(int page, int limit, Object o, String id) {
        // 已办
        List<Letter> list2 = new ArrayList<>();
        // 获取当前登录用户所对应要进行审批处理的数据
        List<Letter> list = baseMapper.selectList(new QueryWrapper<Letter>()
                .eq("do_user", id).or().eq("fen_id", id)
                .or().eq("ke_id", id).or().eq("cheng_user", id));
        if (list == null) {
            return R.ok().data("rows", null).data("total", 0);
        }
        for (Letter leaveing : list) {
            // 代办数量
            Integer integer1 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", leaveing.getId()).eq("middleman_id", id));
            // 已办数量
            Integer integer2 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", leaveing.getId()).eq("handle_id", id));
            // 已办
            if (integer2 >= integer1) {
                list2.add(leaveing);
            }
        }
        return R.ok().data("rows", page(list2, limit, page)).data("total", list2.size());
    }

    public static List<Letter> page(List<Letter> dataList, int pageSize, int currentPage) {
        List<Letter> currentPageList = new ArrayList<>();
        if (dataList != null && dataList.size() > 0) {
            int currIdx = (currentPage > 1 ? (currentPage - 1) * pageSize : 0);
            for (int i = 0; i < pageSize && i < dataList.size() - currIdx; i++) {
                currentPageList.add(dataList.get(currIdx + i));
            }
        }
        return currentPageList;
    }
    /**
     *  信访全部代办
     * @Author wangt
     * @Date 2021-05-07 16:54:04
     */
    @Override
    public R findList(int page, int limit, LetterQueryVo letterQueryVo, String id) {
        ArrayList<LetterListVo> list = new ArrayList<>();
        // 百姓热线
        List<PeopleHotline> peopleHotlineList =addPeo(id,letterQueryVo);
        // 来电
        List<IncomingCall> callList = addCall(id,letterQueryVo);
        // 镇级事项
        List<TownMatter> townMatterList = addTown(id,letterQueryVo);
        // 来信，领导信箱，网信
        List<Letter> letterList = addLett(id,letterQueryVo);
        return findList(page,limit,id,list,peopleHotlineList,callList,townMatterList,letterList);
    }


    /**
     * 代办
     * @Author wangt
     * @Date 2021-05-07 17:56:49
     */
    @Override
    public R listFind(int page, int limit, LetterQueryVo letterQueryVo, String id) {
        ArrayList<LetterListVo> list = new ArrayList<>();
        // 百姓热线
        List<PeopleHotline> peopleHotlineList =addPeo(id,letterQueryVo);
        // 来电
        List<IncomingCall> callList = addCall(id,letterQueryVo);
        // 镇级事项
        List<TownMatter> townMatterList = addTown(id,letterQueryVo);
        // 来信，领导信箱，网信
        List<Letter> letterList = addLett(id,letterQueryVo);
        return listFind(page,limit,id,list,peopleHotlineList,callList,townMatterList,letterList);
    }

    @Override
    public R seleAll(int page, int limit, LetterQueryVo letterQueryVo, String id) {
        ArrayList<LetterListVo> list = new ArrayList<>();
        // 百姓热线
        List<PeopleHotline> peopleHotlineList =addPeo(id,letterQueryVo);
        // 来电
        List<IncomingCall> callList = addCall(id,letterQueryVo);
        // 镇级事项
        List<TownMatter> townMatterList = addTown(id,letterQueryVo);
        // 来信，领导信箱，网信
        List<Letter> letterList = addLett(id,letterQueryVo);
        return selectAll(page,limit,id,list,peopleHotlineList,callList,townMatterList,letterList);
    }
    /**
     * 全部
     * @Author wangt
     * @Date 2021-05-07 17:50:14
     */
    private R selectAll(int page, int limit, String id, ArrayList<LetterListVo> list, List<PeopleHotline> peopleHotlineList, List<IncomingCall> callList, List<TownMatter> townMatterList, List<Letter> letterList) {
        for (PeopleHotline hotline : peopleHotlineList) {
                addVo(list,hotline.getId(),hotline.getLetterTime(),hotline.getDayNum(),hotline.getNum(),hotline.getReplyTime(),hotline.getParty(),
                        hotline.getSource(),hotline.getCategory(),hotline.getLetterTime(),null,3);
        }
        for (IncomingCall call : callList) {
                addVo(list,call.getId(),call.getLetterTime(),call.getDayNum(),call.getNumber(),call.getTermTime(),call.getName(),
                        null,call.getProblem(),call.getLetterTime(),null,4);
        }
        for (TownMatter matter : townMatterList) {
                addVo(list,matter.getId(),matter.getLetterTime(),matter.getDayNum(),matter.getLetterNumber(),matter.getTermTime(),matter.getSourceUser(),
                        matter.getSource(),matter.getContents(),matter.getLetterTime(),null,5);
        }
        for (Letter letter : letterList) {
                addVo(list,letter.getId(),letter.getLetterTime(),letter.getDateNumber(),letter.getLetterNumber(),letter.getTermReply(),letter.getUser(),
                        null,letter.getTitle(),letter.getLetterTime(),letter.getMode(),letter.getTypeSta());

        }
        return R.ok().data("rows",page01(list, limit, page)).data("total",list.size());
    }

    /**
     * 代办
     * @Author wangt
     * @Date 2021-05-07 17:47:02
     */
    private R listFind(int page, int limit, String id, ArrayList<LetterListVo> list, List<PeopleHotline> peopleHotlineList, List<IncomingCall> callList, List<TownMatter> townMatterList, List<Letter> letterList) {
        for (PeopleHotline hotline : peopleHotlineList) {
            // 代办数量
            Integer integer1 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", hotline.getId()).eq("middleman_id", id));
            // 已办数量
            Integer integer2 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", hotline.getId()).eq("handle_id", id));
            // 代办
            if (integer1 > integer2) {
                addVo(list,hotline.getId(),hotline.getLetterTime(),hotline.getDayNum(),hotline.getNum(),hotline.getReplyTime(),hotline.getParty(),
                        hotline.getSource(),hotline.getCategory(),hotline.getLetterTime(),null,3);
            }
        }
        for (IncomingCall call : callList) {
            // 代办数量
            Integer integer1 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", call.getId()).eq("middleman_id", id));
            // 已办数量
            Integer integer2 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", call.getId()).eq("handle_id", id));
            // 代办
            if (integer1 > integer2) {
                addVo(list,call.getId(),call.getLetterTime(),call.getDayNum(),call.getNumber(),call.getTermTime(),call.getName(),
                        null,call.getProblem(),call.getLetterTime(),null,4);
            }
        }
        for (TownMatter matter : townMatterList) {
            // 代办数量
            Integer integer1 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", matter.getId()).eq("middleman_id", id));
            // 已办数量
            Integer integer2 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", matter.getId()).eq("handle_id", id));
            // 代办
            if (integer1 > integer2) {
                addVo(list,matter.getId(),matter.getLetterTime(),matter.getDayNum(),matter.getLetterNumber(),matter.getTermTime(),matter.getSourceUser(),
                        matter.getSource(),matter.getContents(),matter.getLetterTime(),null,5);
            }
        }
        for (Letter letter : letterList) {
            // 代办数量
            Integer integer1 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", letter.getId()).eq("middleman_id", id));
            // 已办数量
            Integer integer2 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", letter.getId()).eq("handle_id", id));
            // 代办
            if (integer1 > integer2) {
                addVo(list,letter.getId(),letter.getLetterTime(),letter.getDateNumber(),letter.getLetterNumber(),letter.getTermReply(),letter.getUser(),
                        null,letter.getTitle(),letter.getLetterTime(),letter.getMode(),letter.getTypeSta());
            }

        }
        return R.ok().data("rows",page01(list, limit, page)).data("total",list.size());
    }

    /**
     * 已办
     * @Author wangt
     * @Date 2021-05-07 17:47:21
     */
    private R findList(int page, int limit,String id, ArrayList<LetterListVo> list,
                       List<PeopleHotline> peopleHotlineList, List<IncomingCall> callList, List<TownMatter> townMatterList, List<Letter> letterList) {
        for (PeopleHotline hotline : peopleHotlineList) {
            // 代办数量
            Integer integer1 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", hotline.getId()).eq("middleman_id", id));
            // 已办数量
            Integer integer2 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", hotline.getId()).eq("handle_id", id));
            // 已办
            if (integer2 >= integer1) {
                addVo(list,hotline.getId(),hotline.getLetterTime(),hotline.getDayNum(),hotline.getNum(),hotline.getReplyTime(),hotline.getParty(),
                        hotline.getSource(),hotline.getCategory(),hotline.getLetterTime(),null,3);
            }
        }
        for (IncomingCall call : callList) {
            // 代办数量
            Integer integer1 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", call.getId()).eq("middleman_id", id));
            // 已办数量
            Integer integer2 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", call.getId()).eq("handle_id", id));
            // 已办
            if (integer2 >= integer1) {
                addVo(list,call.getId(),call.getLetterTime(),call.getDayNum(),call.getLetterNumber(),call.getTermTime(),call.getName(),
                        null,call.getProblem(),call.getLetterTime(),null,4);
            }
        }
        for (TownMatter matter : townMatterList) {
            // 代办数量
            Integer integer1 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", matter.getId()).eq("middleman_id", id));
            // 已办数量
            Integer integer2 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", matter.getId()).eq("handle_id", id));
            // 已办
            if (integer2 >= integer1) {
                addVo(list,matter.getId(),matter.getLetterTime(),matter.getDayNum(),matter.getLetterNumber(),matter.getTermTime(),matter.getSourceUser(),
                        matter.getSource(),matter.getContents(),matter.getLetterTime(),null,5);
            }
        }
        for (Letter letter : letterList) {
            // 代办数量
            Integer integer1 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", letter.getId()).eq("middleman_id", id));
            // 已办数量
            Integer integer2 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", letter.getId()).eq("handle_id", id));
            // 已办
            if (integer2 >= integer1) {
                addVo(list,letter.getId(),letter.getLetterTime(),letter.getDateNumber(),letter.getLetterNumber(),letter.getTermReply(),letter.getUser(),
                        null,letter.getTitle(),letter.getLetterTime(),letter.getMode(),letter.getTypeSta());
            }

        }
        return R.ok().data("rows",page01(list, limit, page)).data("total",list.size());
    }

    private void addVo(ArrayList<LetterListVo> list, String id, Date letterTime, Integer dayNum, String num, Date replyTime,
                       String party, String source, String category, Date letterTime1,String mode,int typeSta) {
        LetterListVo letterListVo = new LetterListVo();
        letterListVo.setId(id);
        letterListVo.setLetterTime(letterTime);
        letterListVo.setDateNumber(dayNum);
        letterListVo.setLetterNumber(num);
        letterListVo.setTermReply(replyTime);
        letterListVo.setUser(party);
        letterListVo.setSource(source);
        letterListVo.setTitle(category);
        letterListVo.setTimes(letterTime1);
        letterListVo.setState("0");
        letterListVo.setMode(mode);
        letterListVo.setTypeSta(typeSta);
        list.add(letterListVo);
    }

    private Object page01(ArrayList<LetterListVo> dataList, int pageSize, int currentPage) {
        List<LetterListVo> currentPageList = new ArrayList<>();
        if (dataList != null && dataList.size() > 0) {
            int currIdx = (currentPage > 1 ? (currentPage - 1) * pageSize : 0);
            for (int i = 0; i < pageSize && i < dataList.size() - currIdx; i++) {
                currentPageList.add(dataList.get(currIdx + i));
            }
        }
        return currentPageList;
    }
    private List<Letter> addLett(String id,LetterQueryVo letterQueryVo) {
        if (letterQueryVo==null){
            return baseMapper.selectList(new QueryWrapper<Letter>()
                    .eq("do_user", id).or().eq("fen_id", id)
                    .or().eq("ke_id", id).or().eq("cheng_user", id));
        }
        QueryWrapper<Letter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("do_user", id).or().eq("fen_id", id)
                .or().eq("ke_id", id).or().eq("cheng_user", id);
        if (!EmptyUtil.isEmpty(letterQueryVo.getLetterNumber())) {
            queryWrapper.like("letter_number",letterQueryVo.getLetterNumber());
        }
        if (!EmptyUtil.isEmpty(letterQueryVo.getLetterTime())){
            queryWrapper.ge("letter_time",letterQueryVo.getLetterTime());
        }
        if (!EmptyUtil.isEmpty(letterQueryVo.getTermReply())){
            queryWrapper.ge("term_reply",letterQueryVo.getTermReply());
        }
        return baseMapper.selectList(queryWrapper);
    }

    private List<TownMatter> addTown(String id,LetterQueryVo letterQueryVo) {
        if (letterQueryVo==null) {
            return townMatterMapper.selectList(new QueryWrapper<TownMatter>()
                    .eq("user_id", id).or().eq("fen_id", id)
                    .or().eq("ke_id", id).or().eq("cheng_user", id));
        }
        QueryWrapper<TownMatter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id).or().eq("fen_id", id)
                .or().eq("ke_id", id).or().eq("cheng_user", id);
        if (!EmptyUtil.isEmpty(letterQueryVo.getLetterNumber())) {
            queryWrapper.like("letter_number",letterQueryVo.getLetterNumber());
        }
        if (!EmptyUtil.isEmpty(letterQueryVo.getLetterTime())){
            queryWrapper.ge("letter_time",letterQueryVo.getLetterTime());
        }
        if (!EmptyUtil.isEmpty(letterQueryVo.getTermReply())){
            queryWrapper.ge("term_time",letterQueryVo.getTermReply());
        }
        return townMatterMapper.selectList(queryWrapper);
    }

    private List<IncomingCall> addCall(String id,LetterQueryVo letterQueryVo) {
        if (letterQueryVo==null) {
            return callMapper.selectList(new QueryWrapper<IncomingCall>()
                    .eq("user_id", id).or().eq("fen_id", id)
                    .or().eq("ke_id", id).or().eq("cheng_user", id));
        }
        QueryWrapper<IncomingCall> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id).or().eq("fen_id", id)
                .or().eq("ke_id", id).or().eq("cheng_user", id);
        if (!EmptyUtil.isEmpty(letterQueryVo.getLetterNumber())) {
            queryWrapper.like("letter_number",letterQueryVo.getLetterNumber());
        }
        if (!EmptyUtil.isEmpty(letterQueryVo.getLetterTime())){
            queryWrapper.ge("letter_time",letterQueryVo.getLetterTime());
        }
        if (!EmptyUtil.isEmpty(letterQueryVo.getTermReply())){
            queryWrapper.ge("term_time",letterQueryVo.getTermReply());
        }
        return callMapper.selectList(queryWrapper);
    }

    private List<PeopleHotline> addPeo(String id,LetterQueryVo letterQueryVo) {
        if (letterQueryVo==null) {
            return peopleHotlineMapper.selectList(new QueryWrapper<PeopleHotline>()
                    .eq("user_id", id).or().eq("fen_id", id)
                    .or().eq("ke_id", id).or().eq("cheng_user", id));
        }
        QueryWrapper<PeopleHotline> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id).or().eq("fen_id", id)
                .or().eq("ke_id", id).or().eq("cheng_user", id);
        if (!EmptyUtil.isEmpty(letterQueryVo.getLetterNumber())) {
            queryWrapper.like("num",letterQueryVo.getLetterNumber());
        }
        if (!EmptyUtil.isEmpty(letterQueryVo.getLetterTime())){
            queryWrapper.ge("letter_time",letterQueryVo.getLetterTime());
        }
        if (!EmptyUtil.isEmpty(letterQueryVo.getTermReply())){
            queryWrapper.ge("reply_time",letterQueryVo.getTermReply());
        }
        return peopleHotlineMapper.selectList(queryWrapper);
    }

    /**
     *校验
     *@author Hugo
     *@date 2021-04-27 14:24
     **/
    void check(Letter letter){
        if (EmptyUtil.isEmpty(letter.getLetterNumber())) {
            throw new SecurityException("信访编号不能为空");
        }
        if (EmptyUtil.isEmpty(letter.getLetterTime())){
            throw new SecurityException("信访时间不能为空！");
        }
        if (EmptyUtil.isEmpty(letter.getTermReply())){
            throw new SecurityException("答复时间不能为空！");
        }
        if (letter.getLetterTime().getTime() >= letter.getTermReply().getTime()) {
            throw new SecurityException("答复日期不能小于信访日期！");
        }
        if (EmptyUtil.isEmpty(letter.getTermReply())) {
            throw new SecurityException("期限答复不能为空");
        }
        if (EmptyUtil.isEmpty(letter.getDateNumber())) {
            throw new SecurityException("限办天数不能为空");
        }
        if (EmptyUtil.isEmpty(letter.getUser())) {
            throw new SecurityException("信访人不能为空");
        }
        if (EmptyUtil.isEmpty(letter.getVerifying())) {
            throw new SecurityException("证件号码不能为空");
        }
        if (EmptyUtil.isEmpty(letter.getTel())) {
            throw new SecurityException("电话号码不能为空");
        }
        if (EmptyUtil.isEmpty(letter.getAddress())) {
            throw new SecurityException("信访人地址为空");
        }
        if (EmptyUtil.isEmpty(letter.getTitle())) {
            throw new SecurityException("标题为空");
        }
        if (EmptyUtil.isEmpty(letter.getLetterTime())) {
            throw new SecurityException("信访日期为空");
        }
        if (EmptyUtil.isEmpty(letter.getContent())) {
            throw new SecurityException("信访内容为空");
        }
        if (EmptyUtil.isEmpty(letter.getDoUser())) {
            throw new SecurityException("请选择经办人！");
        }
        if (EmptyUtil.isEmpty(letter.getFenId())){
            throw new SecurityException("请选择分管领导！");
        }
    }
    
    @Override
    public IPage<Letter> selectPage(Page<Letter> pageParam, Object o) {
        return baseMapper.selectPage(pageParam,null);
    }

    /**
     * 信访总数 以及信访总数折线图
     *
     */
    @Override
    public R num() {
        Calendar cal = Calendar.getInstance();
        // 当前年
        int year = cal.get(Calendar.YEAR);
        QueryWrapper<Letter> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.like("letter_time",year);
        Integer integer2 = baseMapper.selectCount(queryWrapper2);
        // 去年
        int year1 = cal.get(Calendar.YEAR)-1;
        QueryWrapper<Letter> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.like("letter_time",year1);
        Integer integer1 = baseMapper.selectCount(queryWrapper1);
        int i;
        // 存放当前年
        List<Integer> result = new ArrayList<>();
        for (i=1;i<=12;i++){
            // 当前年总数
            if (i<=9){
                String time= year+"-"+"0"+i;
                QueryWrapper<Letter> queryWrapper = new QueryWrapper<>();
                queryWrapper.like("letter_time",time);
                Integer integer = baseMapper.selectCount(queryWrapper);
                result.add(integer);
            }else {
                String time= year+"-"+i;
                QueryWrapper<Letter> queryWrapper = new QueryWrapper<>();
                queryWrapper.like("letter_time",time);
                Integer integer = baseMapper.selectCount(queryWrapper);
                result.add(integer);
            }
        }
        // 百分比
        String xx = bizhi(integer2,integer1);
        return R.ok().message("成功！").data("num",integer2).data("result",result).data("bizhi",xx);
    }



    /**
     * 已办总数以及树状图
     *
     */
    @Override
    public R alreadyNum() {
        Calendar cal = Calendar.getInstance();
        //当前年
        int year = cal.get(Calendar.YEAR);
        QueryWrapper<Letter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state",0)
                .like("letter_time",year);
        Integer integer2 = baseMapper.selectCount(queryWrapper);
        //去年
        int year1 = cal.get(Calendar.YEAR)-1;
        Integer integer1 = baseMapper.selectCount(queryWrapper(0,year1));
        int i;
        List<Integer> result = new ArrayList<>();
        for (i=1;i<=12;i++){
            // 当前年
            if (i<=9){
                String time= year+"-"+"0"+i;
                QueryWrapper<Letter> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.like("letter_time",time);
                queryWrapper1.eq("state","0");
                Integer integer = baseMapper.selectCount(queryWrapper1);
                result.add(integer);
            }else {
                String time= year+"-"+i;
                QueryWrapper<Letter> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.like("letter_time",time);
                queryWrapper1.eq("state","0");
                Integer integer = baseMapper.selectCount(queryWrapper1);
                result.add(integer);
            }
        }
        // 百分比
        String xx = bizhi(integer2,integer1);
        return R.ok().message("成功！").data("num",integer2).data("result",result).data("bizhi",xx);
    }

    private Wrapper<Letter> queryWrapper(int i, int year) {
        QueryWrapper<Letter> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("state",i);
        queryWrapper.like("letter_time",year);
        return queryWrapper;
    }

    /**
     * 代办总数
     *
     */
    @Override
    public R waitNum() {
        Calendar cal = Calendar.getInstance();
        // 获取当前年
        int year = cal.get(Calendar.YEAR);
        // .or(s -> s.eq("state","0").or().eq("state","2").or().eq("state","3"));
        Integer integer2 = baseMapper.selectCount(queryWrapper(0,year));
        // 去年
        int year1 = cal.get(Calendar.YEAR)-1;
        Integer integer1 = baseMapper.selectCount(queryWrapper(0,year1));
        int i;
        List<Integer> result = new ArrayList<>();
        for (i=1;i<=12;i++){
            if (i<=9){
                String time= year+"-"+"0"+i;
                QueryWrapper<Letter> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.like("letter_time",time).ne("state","0");

                Integer integer = baseMapper.selectCount(queryWrapper1);
                result.add(integer);
            }else {
                String time= year+"-"+i;
                QueryWrapper<Letter> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.like("letter_time",time).ne("state","0");
                Integer integer = baseMapper.selectCount(queryWrapper1);
                result.add(integer);
            }
        }
        // 百分比
        String xx = bizhi(integer2,integer1);
        return R.ok().message("成功").data("num",integer2).data("result",result).data("bizhi",xx);
    }

    /**
     * 柱状图
     * @Author: wangt
     */
    @Override
    public R stateZhu() {
        Calendar cal = Calendar.getInstance();
        // 获取当前年
        int year = cal.get(Calendar.YEAR);
        List<LetterStateVo> list = new ArrayList<>();
        // 正常进行
        QueryWrapper<Letter> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.like("letter_time",year);
        queryWrapper1.eq("state_type","0");
        queryWrapper1.ne("state","0");
        Integer zJin = baseMapper.selectCount(queryWrapper1);
        LetterStateVo letterStateVo = new LetterStateVo();
        letterStateVo.setValue(zJin);
        letterStateVo.setName("正常进行");
        list.add(letterStateVo);
        // 逾期进行
        QueryWrapper<Letter> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.like("letter_time",year);
        queryWrapper4.eq("state_type","1");
        queryWrapper4.ne("state","0");
        Integer yJin = baseMapper.selectCount(queryWrapper4);
        LetterStateVo letterStateVo1 = new LetterStateVo();
        letterStateVo1.setValue(yJin);
        letterStateVo1.setName("逾期进行");
        list.add(letterStateVo1);
        // 正常完成
        QueryWrapper<Letter> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.like("letter_time",year);
        queryWrapper2.eq("state_type","0");
        queryWrapper2.eq("state","0");
        Integer zWan = baseMapper.selectCount(queryWrapper2);
        LetterStateVo letterStateVo2 = new LetterStateVo();
        letterStateVo2.setValue(zWan);
        letterStateVo2.setName("正常完成");
        list.add(letterStateVo2);
        // 逾期完成
        QueryWrapper<Letter> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.like("letter_time",year);
        queryWrapper3.eq("state_type","1");
        queryWrapper3.eq("state","0");
        Integer yWan = baseMapper.selectCount(queryWrapper3);
        LetterStateVo letterStateVo3 = new LetterStateVo();
        letterStateVo3.setValue(yWan);
        letterStateVo3.setName("逾期完成");
        list.add(letterStateVo3);
        return R.ok().message("成功！").data("list",list);
    }

    /**
     * 根据ID查询
     *
     *
     */
    @Override
    public Object findById(String id) {
        return baseMapper.selectById(id);
    }

    private Wrapper<Letter> stateQuery(int year, String s) {
        QueryWrapper<Letter> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("letter_time",year);
        queryWrapper.eq("state_type",s);
        return queryWrapper;
    }

    /***
     *百分比
     */
    private String bizhi(Integer integer2, Integer integer1) {
        if (integer1 != 0 && integer2 !=0){
            double num2 = integer2;
            double num1 = integer1;
            NumberFormat formatter = new DecimalFormat("0.00");
            double x= (num2 / num1) * 100;
            return formatter.format(x);
        }
        return "0.00";
    }
}
